﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace pklib.ViewModel {
	public class ViewModelBase<ModelT> : INotifyPropertyChanged {
		#region INotifyPropertyChanged
			public event PropertyChangedEventHandler PropertyChanged;
		#endregion

		private ModelT _Target = default(ModelT);
		public ModelT Target { get { return this._Target; } protected set { this._Target = value; } }

		public ViewModelBase() {

		}

		public ViewModelBase(ModelT Target) : base() {
			this.SetTarget(Target);
		}

		public object SetTarget(ModelT Target) {
			if (null != this.Target)
				(this.Target as INotifyPropertyChanged).PropertyChanged -= this.OnTargetPropertyChanged;

			this.Target = Target;

			if (null != this.Target)
				(this.Target as INotifyPropertyChanged).PropertyChanged += this.OnTargetPropertyChanged;

			return this;
		}

		void OnTargetPropertyChanged(object sender, PropertyChangedEventArgs e) {
			this.PropertyChanged(this, e);
		}

		public virtual void OnPropertyChanged(string propertyName) {
			if (this.PropertyChanged != null) {
				this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
			}
		}

		public static implicit operator ModelT(ViewModelBase<ModelT> vmb) {
			return vmb.Target;
		}
	}
}
